#include "mystdio.h"

_FILE* _fopen(const char* path, const char* mode)
{
    int flag = 0;
    int defaultMode = 0666;
    if(strcmp(mode,"r") == 0)
    {
        flag |= O_RDONLY;
    }
    else if(strcmp(mode,"w") == 0)
    {
        flag |= O_WRONLY | O_CREAT | O_TRUNC;
    }
    else if(strcmp(mode,"a") == 0)
    {
        flag | O_WRONLY | O_CREAT | O_APPEND;
    }
    else 
    {}

    int fd = 0;
    if(flag & O_RDONLY) fd = open(path,flag);
    else    fd = open(path,flag,defaultMode);

    if(fd < 0)
    {
        char str[] = "open fail\n";
        write(stdout->_fileno,str,strlen(str));
        return nullptr;
    }
    _FILE* fp = new _FILE;
    fp->_fileno = fd;
    fp->_flag = SYNC_LINE;
    fp->_size = 0;
    memset(fp->_buffer,0,MAX_SIZE);

    return fp;
}

void _fflush(_FILE* fp)
{
    if(fp->_size > 0)   write(fp->_fileno,fp->_buffer,fp->_size);
    fsync(fp->_fileno); //强制要求OS进行外设刷新
    fp->_size = 0;
}

void _fwrite(const char* ptr, size_t size, _FILE* fp)
{
    memcpy(fp->_buffer+fp->_size,ptr,size); //不考虑溢出问题
    fp->_size += size;
    if(fp->_flag == SYNC_NOW)
    {
        write(fp->_fileno,fp->_buffer,fp->_size);
        fp->_size = 0;
    }
    else if(fp->_flag == SYNC_LINE)
    {
        if(fp->_buffer[strlen(fp->_buffer)-1] == '\n') //不考虑 "abc/ncde"这种情况
        {
            write(fp->_fileno,fp->_buffer,fp->_size);
            fp->_size = 0;
        }
    }
    else if(fp->_flag == SYNC_FULL)
    {
        if(fp->_size == MAX_SIZE)
        {
            write(fp->_fileno,fp->_buffer,fp->_size);
            fp->_size = 0;
        }
    }
}


void _fread(void* ptr, size_t size, _FILE* fp)
{
    
    read(fp->_fileno,ptr,size);
    ((char*)ptr)[size] = 0;
}


void _fclose(_FILE* fp)
{
    _fflush(fp);
    close(fp->_fileno);
}